package com.shlh.saas.service.canton.exhibitor.impl;

import com.shlh.saas.common.Desensitization;
import com.shlh.saas.entity.canton.exhibitor.BaseCantonFairExhibitor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 广交会展商服务抽象基类
 * 提供通用的数据处理和转换逻辑
 */
@Slf4j
public abstract class AbstractCantonFairExhibitorService {

    @Autowired
    protected Desensitization desensitization;

    /**
     * 通用的BaseCantonFairExhibitor转换方法
     *
     * @param exhibitor           原始展商对象
     * @param sessionInfo         届数信息
     * @param needDesensitization 是否需要脱敏
     * @return 转换后的BaseCantonFairExhibitor对象
     */
    protected BaseCantonFairExhibitor convertToBaseExhibitor(Object exhibitor, String sessionInfo, boolean needDesensitization) {
        if (exhibitor == null) {
            return null;
        }

        BaseCantonFairExhibitor baseExhibitor = new BaseCantonFairExhibitor();

        try {
            // 使用反射获取通用字段
            Class<?> clazz = exhibitor.getClass();

            // 设置基本信息
            setFieldValue(baseExhibitor, "id", getFieldValue(exhibitor, "id"));
            setFieldValue(baseExhibitor, "companyName", getFieldValue(exhibitor, "companyName"));
            setFieldValue(baseExhibitor, "period", getFieldValue(exhibitor, "period"));
            setFieldValue(baseExhibitor, "boothNumber", getFieldValue(exhibitor, "boothNumber"));
            setFieldValue(baseExhibitor, "category", getFieldValue(exhibitor, "category"));
            setFieldValue(baseExhibitor, "contactPerson", getFieldValue(exhibitor, "contactPerson"));
            setFieldValue(baseExhibitor, "address", getFieldValue(exhibitor, "contactAddress"));
            setFieldValue(baseExhibitor, "postalCode", getFieldValue(exhibitor, "postalCode"));
            setFieldValue(baseExhibitor, "city", getFieldValue(exhibitor, "city"));
            setFieldValue(baseExhibitor, "province", getFieldValue(exhibitor, "provinceCity"));
            setFieldValue(baseExhibitor, "session", getFieldValue(exhibitor, "session"));
            setFieldValue(baseExhibitor, "establishmentYear", getFieldValue(exhibitor, "establishmentYear"));


//            setFieldValue(baseExhibitor, "principalName", getFieldValue(exhibitor, "principalName"));
//            setFieldValue(baseExhibitor, "principalPosition", getFieldValue(exhibitor, "principalPosition"));
//            setFieldValue(baseExhibitor, "principalMobile", getFieldValue(exhibitor, "principalMobile"));
//            setFieldValue(baseExhibitor, "principalPhone", getFieldValue(exhibitor, "principalPhone"));


            // 设置扩展字段
            Map<String, Object> extendedFields = new HashMap<>();
            extendedFields.put("sessionInfo", sessionInfo);

            // 添加其他扩展字段
            addExtendedField(extendedFields, exhibitor, "mainProducts");
            addExtendedField(extendedFields, exhibitor, "principalName");
            addExtendedField(extendedFields, exhibitor, "principalPosition");
            addExtendedField(extendedFields, exhibitor, "companyType");
            addExtendedField(extendedFields, exhibitor, "companyScale");
//          addExtendedField(extendedFields, exhibitor, "establishmentYear");
//          addExtendedField(extendedFields, exhibitor, "principalMobile");
//          addExtendedField(extendedFields, exhibitor, "principalPhone");
            addExtendedField(extendedFields, exhibitor, "recentExhibitionHistory");
            addExtendedField(extendedFields, exhibitor, "fax");
            addExtendedField(extendedFields, exhibitor, "registeredCapital");
            addExtendedField(extendedFields, exhibitor, "companyProfile");

            // 处理联系信息（根据是否需要脱敏）
            if (needDesensitization) {
                addDesensitizedContactInfo(extendedFields, exhibitor);
            } else {
                addRawContactInfo(extendedFields, exhibitor);
            }

            baseExhibitor.setExtendedFields(extendedFields);

        } catch (Exception e) {
            log.error("转换BaseCantonFairExhibitor失败", e);
        }

        return baseExhibitor;
    }

    /**
     * 添加脱敏的联系信息
     */
    private void addDesensitizedContactInfo(Map<String, Object> extendedFields, Object exhibitor) {
        String mobile = (String) getFieldValue(exhibitor, "mobile");
        String phone = (String) getFieldValue(exhibitor, "phone");
        String fax = (String) getFieldValue(exhibitor, "fax");
        String email = (String) getFieldValue(exhibitor, "email");
        String website = (String) getFieldValue(exhibitor, "website");
        if (!(getFieldValue(exhibitor, "principalMobile") == null)){
            String principalMobile = getFieldValue(exhibitor, "principalMobile").toString();
            extendedFields.put("principalMobile", desensitization.maskPhone(principalMobile));

        }
        if (!(getFieldValue(exhibitor, "principalPhone") == null)){
            String principalPhone = getFieldValue(exhibitor, "principalPhone").toString();
            extendedFields.put("principalPhone", desensitization.maskPhone(principalPhone));
        }

        if (!Objects.equals(mobile, "-")) {
            extendedFields.put("mobilePhone", desensitization.maskPhone(mobile));
        }
        if (!Objects.equals(phone, "-")) {
            extendedFields.put("phone", desensitization.maskPhone(phone));
        }
        if (!Objects.equals(fax, "-")) {
            extendedFields.put("fax", desensitization.maskPhone(fax));
        }
        if (!Objects.equals(email, "-")){
            extendedFields.put("email", desensitization.maskEmail(email));
        }
        if (!Objects.equals(website, "-")){
            extendedFields.put("website", desensitization.maskWebAddress(website));
        }
    }

    /**
     * 添加原始联系信息（不脱敏）
     */
    private void addRawContactInfo(Map<String, Object> extendedFields, Object exhibitor) {
        extendedFields.put("mobilePhone", getFieldValue(exhibitor, "mobile"));
        extendedFields.put("phone", getFieldValue(exhibitor, "phone"));
        extendedFields.put("fax", getFieldValue(exhibitor, "fax"));
        extendedFields.put("email", getFieldValue(exhibitor, "email"));
        extendedFields.put("website", getFieldValue(exhibitor, "website"));
        if (!(getFieldValue(exhibitor, "principalMobile") == null)){
            extendedFields.put("principalMobile", getFieldValue(exhibitor, "principalMobile"));
        }
        if (!(getFieldValue(exhibitor, "principalPhone") == null)){
            extendedFields.put("principalPhone", getFieldValue(exhibitor, "principalPhone"));
        }
    }

    /**
     * 添加扩展字段
     */
    private void addExtendedField(Map<String, Object> extendedFields, Object exhibitor, String fieldName) {
        Object value = getFieldValue(exhibitor, fieldName);
        if (value != null) {
            extendedFields.put(fieldName, value);
        }
    }

    /**
     * 通过反射获取字段值
     */
    protected Object getFieldValue(Object obj, String fieldName) {
        try {
            Field field = findField(obj.getClass(), fieldName);
            if (field != null) {
                field.setAccessible(true);
                return field.get(obj);
            }
        } catch (Exception e) {
            log.debug("获取字段值失败: {}.{}", obj.getClass().getSimpleName(), fieldName);
        }
        return null;
    }

    /**
     * 通过反射设置字段值
     */
    protected void setFieldValue(Object obj, String fieldName, Object value) {
        try {
            Field field = findField(obj.getClass(), fieldName);
            if (field != null && value != null) {
                field.setAccessible(true);
                field.set(obj, value);
            }
        } catch (Exception e) {
            log.debug("设置字段值失败: {}.{}", obj.getClass().getSimpleName(), fieldName);
        }
    }

    /**
     * 查找字段（包括父类）
     */
    private Field findField(Class<?> clazz, String fieldName) {
        while (clazz != null) {
            try {
                return clazz.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
                clazz = clazz.getSuperclass();
            }
        }
        return null;
    }

    /**
     * 通过反射获取指定字段的值（用于联系信息查询）
     */
    protected String getFieldValueByName(Object exhibitor, String fieldName) {
        if (exhibitor == null || !StringUtils.hasText(fieldName)) {
            return null;
        }

        try {
            Field field = findField(exhibitor.getClass(), fieldName);
            if (field != null) {
                field.setAccessible(true);
                Object value = field.get(exhibitor);
                return value != null ? value.toString() : null;
            }
        } catch (Exception e) {
            log.error("获取字段值失败: {}.{}", exhibitor.getClass().getSimpleName(), fieldName, e);
        }

        return null;
    }

    /**
     * 构建搜索关键词的SQL条件
     */
    protected String buildKeywordSearchCondition(String keyword, List<String> searchFields) {
        if (!StringUtils.hasText(keyword) || searchFields == null || searchFields.isEmpty()) {
            return "";
        }

        StringBuilder condition = new StringBuilder();
        condition.append("(");

        for (int i = 0; i < searchFields.size(); i++) {
            if (i > 0) {
                condition.append(" OR ");
            }
            condition.append(searchFields.get(i)).append(" LIKE '%").append(keyword).append("%'");
        }

        condition.append(")");
        return condition.toString();
    }

    /**
     * 构建筛选条件的SQL
     * 返回不带AND前缀的条件，由调用方决定如何连接
     */
    protected String buildFilterCondition(String companyType, String companyScale, String product, String hasContact) {
        StringBuilder condition = new StringBuilder();
        boolean hasCondition = false;

        // 公司类型
        if (StringUtils.hasText(companyType)) {
            String[] types = companyType.split(",");
            if (hasCondition) {
                condition.append(" AND ");
            }
            condition.append("(");
            for (int i = 0; i < types.length; i++) {
                if (i > 0) {
                    condition.append(" OR ");
                }
                condition.append("company_type = '").append(types[i].trim()).append("'");
            }
            condition.append(")");
            hasCondition = true;
        }

        if (StringUtils.hasText(product)) {
            String[] products = product.split(",");
            if (hasCondition) {
                condition.append(" AND ");
            }
            condition.append("(");
            for (int i = 0; i < products.length; i++) {
                if (i > 0) {
                    condition.append(" OR ");
                }
                condition.append("main_products LIKE '%").append(products[i].trim()).append("%'");
            }
            condition.append(")");
            hasCondition = true;
        }

        // 公司规模
        if (StringUtils.hasText(companyScale)) {
            String[] scales = companyScale.split(",");
            if (hasCondition) {
                condition.append(" AND ");
            }
            condition.append("(");
            for (int i = 0; i < scales.length; i++) {
                if (i > 0) {
                    condition.append(" OR ");
                }
                condition.append("company_scale = '").append(scales[i].trim()).append("'");
            }
            condition.append(")");
            hasCondition = true;
        }

        // 添加联系方式筛选条件
        if (StringUtils.hasText(hasContact)) {
            if(hasContact.contains("phone")){
                if (hasCondition) {
                    condition.append(" AND ");
                }
                condition.append("phone IS NOT NULL AND phone != '' ");
                hasCondition = true;
            }
            if(hasContact.contains("mobile")){
                if (hasCondition) {
                    condition.append(" AND ");
                }
                condition.append("mobile IS NOT NULL AND mobile != '' ");
                hasCondition = true;
            }
            if(hasContact.contains("email")){
                if (hasCondition) {
                    condition.append(" AND ");
                }
                condition.append("email IS NOT NULL AND email != '' ");
                hasCondition = true;
            }
            if (hasContact.contains("fax")){
                if (hasCondition) {
                    condition.append(" AND ");
                }
                condition.append("fax IS NOT NULL AND fax != '' ");
                hasCondition = true;
            }
            if (hasContact.contains("website")) {
                if (hasCondition) {
                    condition.append(" AND ");
                }
                condition.append("website IS NOT NULL AND website != '' ");
                hasCondition = true;
            }
            hasCondition = true;
        }

        return condition.toString();
    }

    /**
     * 验证届数参数
     */
    protected boolean isValidSession(String sessionInfo, String targetSession) {
        return StringUtils.hasText(sessionInfo) && sessionInfo.contains(targetSession);
    }

    /**
     * 安全地转换为整数
     */
    protected int safeToInt(Object value, int defaultValue) {
        if (value == null) {
            return defaultValue;
        }

        try {
            if (value instanceof Number) {
                return ((Number) value).intValue();
            } else {
                return Integer.parseInt(value.toString());
            }
        } catch (NumberFormatException e) {
            log.debug("转换整数失败: {}", value);
            return defaultValue;
        }
    }

    /**
     * 安全地转换为长整数
     */
    protected long safeToLong(Object value, long defaultValue) {
        if (value == null) {
            return defaultValue;
        }

        try {
            if (value instanceof Number) {
                return ((Number) value).longValue();
            } else {
                return Long.parseLong(value.toString());
            }
        } catch (NumberFormatException e) {
            log.debug("转换长整数失败: {}", value);
            return defaultValue;
        }
    }
}
